function MyWebSocket(serviceName, config) {
  this.serviceName = serviceName;
  this.config = config;
  this.maxReconnectCount = 2;
  this.curReconnectCount = 0;
  this.timer = null;
  this.connect();
}

MyWebSocket.prototype.connect = function () {
  var _me = this;
  var serverIp = location.hostname;
  var _config = _me.config;
  // 需要判断是否支持websocket，如果不支持，使用flash版本的
  if (typeof WebSocket != "undefined") {
    initWebSocket();
    _me.supportWebSocket = true;
  } else {
    console.log("not support Websocket");
    _me.supportWebSocket = false;
    return;
  }

  function initWebSocket() {
    var url = `${_config.params.url}`;

    var socket = new WebSocket(url);
    _me.socket = socket;

    socket.onopen = function (res) {
      this.curReconnectCount = 0;
      _config.onopen(res);
      clearTimeout(this.timer);
    };

    socket.onmessage = function (message) {
      _config.onmessage(message.data);
    };

    socket.onclose = function (err) {
      _config.onclose(err);
    };

    socket.onerror = function (err) {
      _config.onerror(err);
    };
  }
};

MyWebSocket.prototype.send = function (message) {
  if (this.supportWebSocket) {
    this.socket.send(JSON.stringify(message));
  } else {
    this.socket.sendRequest(this.serviceName, message, true);
  }
};

MyWebSocket.prototype.close = function () {
  if (this.supportWebSocket) {
    this.socket.close();
    this.timer && clearTimeout(this.timer);
  } else {
    this.socket.disconnect();
  }
};

MyWebSocket.prototype.reconnect = function () {
  this.timer = setTimeout(() => {
    this.curReconnectCount++;
    if (this.curReconnectCount > this.maxReconnectCount) {
      clearTimeout(this.timer);
      return;
    }
    // if (this.curReconnectCount > this.maxReconnectCount) return;
    console.log("ws reconnect time", this.curReconnectCount);
    this.close();
    this.connect();
  }, 5000);
};

export default MyWebSocket;
